const Utils = require('../../../utils'); // 工具函数
const LinkInfoTalk = require('../../../models/blog_info_talk');

/**
 * 留言管理控制器
 */
const ControllerTalk = {
    /* 列表 */
    getList: async function (req, res, next) {
        try {
            const { per_page, page } = req.query;

            const all = await LinkInfoTalk.all();
            const getComment = Utils.getData(all); //* 树形数据处理索引0为一级，其他均为子级
            const commentData = Utils.getChildrenTree(getComment, getComment[0]); //* 按父子关系处理分类
            const list = Utils.getPagination(commentData, per_page, page);

            list.sort((a, b) => {
                return a.id - b.id
            })

            res.json({ code: 200, msg: '查询完成', data: { list, total: all.length } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    /* 详情 */
    getById: async function (req, res, next) {
        try {
            const { id } = req.query;
            const list = await LinkInfoTalk.select({ id });
            list[0].content = decodeURI(list[0].content);
            list[0].reply_content = decodeURI(list[0].reply_content);

            res.json({ code: 200, msg: '获得列表', data: { list: list[0] } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    /* 添加 */
    Insert: async function (req, res, next) {
        try {
            const { id, content } = req.body;

            let params = { content: encodeURI(content), name: '闲云野鹤', master: 1, created_time: new Date().getTime() };

            if (id) {
                const item = await LinkInfoTalk.select({ id })
                params.pid = item[0].pid ? item[0].pid : id;
                params.reply_id = id;
                params.reply_name = item[0].name;
                params.reply_content = item[0].content;
                params.reply_master = item[0].master;
            }

            await LinkInfoTalk.insert(params);

            res.json({ code: 200, msg: '成功新增留言', data: {} })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    /* 删除 */
    del: async function (req, res, next) {
        try {
            const { id } = req.body;
            const list = await LinkInfoTalk.select({ pid: id })
            const ids = list.map(i => i.id);
            ids.push(id)
            await LinkInfoTalk.batchDel(ids)

            res.json({ code: 200, msg: '成功删除', data: {} })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
}

module.exports = ControllerTalk;
